﻿<%@ WebHandler Language="C#" Class="detail" %>
using System;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Web.Configuration;
using Models;
using System.Linq;
public class detail : IHttpHandler {


    public static string APPID =WebConfigurationManager.AppSettings["APPID"];
    public static string APPSECRET =WebConfigurationManager.AppSettings["APPSECRET"];
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";


        //string postdata=Utils.PostInput(context);

        //   JObject jo = (JObject)JsonConvert.DeserializeObject(postdata);
        //    string js_code = jo["code"].ToString();



          var js_code=HttpContext.Current.Request.QueryString["code"];




        if (string.IsNullOrEmpty(js_code))
        {
            HttpContext.Current.Response.Write("parameter error");
            return;
        }

        string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=" +APPID+ "&secret=" +APPSECRET+ "&js_code=" + js_code + "&grant_type=authorization_code";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
        request.Method = "GET";
        request.ContentType = "text/html;charset=utf-8";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();


        var mybacktoken = JObject.Parse(retString);
        var authtoken=mybacktoken["openid"].ToString();

            var code=0;
              using (Entities bll = new Entities())
                 {
             var x = bll.User.FirstOrDefault(p => p.UOpenID == authtoken);
               if (x==null) //没有这个用户
                code=1;
               
        var data = new
        {
            userinfo=x,
            data=mybacktoken,
            code,
            msg = "获取session_key",
            time = DateTime.Now
        };
            
        Formatting microsoftDataFormatSettings = default(Formatting);
        string result = JsonConvert.SerializeObject(data, microsoftDataFormatSettings);

        context.Response.Write(result);

    }

        HttpContext.Current.Response.End();
        //context.Response.Write("Hello World");


    }





    public bool IsReusable {
        get {
            return false;
        }
    }

}